package com.vanke.kotlin

import android.content.Context
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * @name Kotlin
 * @package name：com.vanke.kotlin
 * @class describe
 * @anthor shiyuchuan
 * @time 2017/8/2 15:25
 */
class Prefrence<T>(val context: Context,val name: String, val default: T)
    : ReadWriteProperty<Any?,T>{

    val prefs by lazy { context.getSharedPreferences("default",Context.MODE_PRIVATE) }

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return findPrefrence(name,default)
    }

    private fun <T> findPrefrence(name: String, default: T): T = with(prefs){
        val res: Any = when(default){
            is Long -> getLong(name,default)
            is String -> getString(name,default)
            is Int -> getInt(name,default)
            is Boolean -> getBoolean(name,default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException()
        }
        res as T
    }
    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        putPrefrence(name,default)
    }

    private fun <U> putPrefrence(name: String, value: U) = with(prefs.edit()){
        when(value){
            is  Long -> putLong(name, value)
            is String -> putString(name,value)
            is Int -> putInt(name,value)
            is Boolean -> putBoolean(name,value)
            is Float -> putFloat(name,value)
            else -> throw IllegalArgumentException()
        }.apply()

    }


}